<template>
  <div class="hmi-batch-update">
    <HmiBatchUpdateTable
      :config="config"
      :readonly="readonly"
      :show-toolbar="showToolbar"
      :show-export="showExport"
      :show-actions="showActions"
      :selectable="selectable"
      @save-success="handleSaveSuccess"
      @save-error="handleSaveError"
      @selection-change="handleSelectionChange"
    />
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted } from "vue";
import { useRoute } from "vue-router";
import { useHmiConfigStore, useSettingZoneStore } from "@/store";
import HmiBatchUpdateTable from "./HmiBatchUpdateTable.vue";
import type { HmiBatchUpdateConfig, HmiTableRow } from "./types";

interface Props {
  // 基础配置
  apiPath?: string;
  updateApi?: string;
  idKey?: string;
  valueKey?: string;
  enumKey?: string;
  updateIdKey?: string;
  updateValueKey?: string;
  updateBodyKey?: string[];

  // 显示配置
  readonly?: boolean;
  showToolbar?: boolean;
  showExport?: boolean;
  showActions?: boolean;
  selectable?: boolean;

  // 分页配置
  pageSize?: number;
  showSizeChanger?: boolean;

  // 定值区配置
  showSettingZone?: boolean;
}

interface Emits {
  (_e: "save-success", _data: any): void;
  (_e: "save-error", _error: Error): void;
  (_e: "selection-change", _selection: HmiTableRow[]): void;
}

const props = withDefaults(defineProps<Props>(), {
  readonly: false,
  showToolbar: true,
  showExport: true,
  showActions: true,
  selectable: false,
  pageSize: 10,
  showSizeChanger: true,
  showSettingZone: false,
});

const emit = defineEmits<Emits>();

// Store
const route = useRoute();
const hmiConfigStore = useHmiConfigStore();
const settingZoneStore = useSettingZoneStore();

// 配置计算
const config = computed<HmiBatchUpdateConfig>(() => {
  // 从路由或 props 获取 API 路径
  const apiPath = props.apiPath || (route?.meta?.params as any)?.api || "";

  // 从 HMI 配置获取表格规则
  // const tableRule = hmiConfigStore.getTableHeaderRuleByUri(apiPath);
  const tableRule = hmiConfigStore.getTableHeaderRuleByPath(route.path);
  const batchUpdateRule = tableRule?.columnRule?.batchUpdate || [];
  const batchUpdateOptions = tableRule?.showRule?.batchUpdateOptions || {};

  // 构建列配置
  const columns = batchUpdateRule
    .slice()
    .sort((a, b) => (a.index ?? 0) - (b.index ?? 0))
    .map((rule) => ({
      ...rule,
      key: rule.key || "",
      label: rule.label || "",
      type: determineColumnType(rule),
      editable: true, // 默认可编辑
      required: false, // 默认非必填
    }));
  // console.log(tableRule);
  // console.log(columns, ":", batchUpdateRule);
  console.log(batchUpdateOptions);
  return {
    apiPath,
    updateApi: batchUpdateOptions.updateApi,
    idKey: batchUpdateOptions.idKey || "id",
    valueKey: batchUpdateOptions.valueKey || "value",
    enumKey: batchUpdateOptions.enumKey,
    updateIdKey: batchUpdateOptions.updateIdKey || "id",
    updateValueKey: batchUpdateOptions.updateValueKey || "value",
    updateBodyKey: batchUpdateOptions.updateBodyKey || [],
    updateBodyConfig: batchUpdateOptions.updateBodyConfig || {},
    columns,
    showSettingZone: props.showSettingZone,
    showAutoSetButton: batchUpdateOptions.showAutoSetButton || false,
    autoSetApi: batchUpdateOptions.autoSetApi || "",
    pagination: {
      pageSize: props.pageSize,
      showSizeChanger: props.showSizeChanger,
    },
    group: batchUpdateOptions.group || "",
    orderByKey: batchUpdateOptions.orderByKey || "",
    enableAutoRefresh: batchUpdateOptions.enableAutoRefresh || false, // 默认不启用
  };
});

// 计算定值区 API 路径
const settingZoneApi = computed(() => {
  const tableRule = hmiConfigStore.getTableHeaderRuleByPath(route.path);
  return tableRule?.showRule?.batchUpdateOptions?.settingZoneApi || "/setting/1/zone";
});

// 确定列类型
function determineColumnType(rule: any): "enum" | "number" | "string" | "boolean" {
  if (rule.type) return rule.type;
  if (rule.enumOptions) return "enum";
  if (rule.inputType === "number") return "number";
  if (rule.inputType === "boolean") return "boolean";
  return "string";
}

// 事件处理
function handleSaveSuccess(data: any) {
  emit("save-success", data);
}

function handleSaveError(error: Error) {
  emit("save-error", error);
}

function handleSelectionChange(selection: HmiTableRow[]) {
  emit("selection-change", selection);
}

// 初始化
onMounted(async () => {
  try {
    await hmiConfigStore.initHmiConfig();
    if (props.showSettingZone) {
      await settingZoneStore.fetchSettingZoneInfo(settingZoneApi.value);
    }
  } catch (error) {
    console.error("HmiBatchUpdate 初始化失败:", error);
  }
});
</script>

<style scoped>
.hmi-batch-update {
  width: 100%;
  height: 100%;
}
</style>
